package cc.laop.ftp;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: Pengpeng
 * @Date: create in 2018/1/2 9:53
 * @Description:
 */
public class FileUpdateCheck {

    public static boolean check(String absolutePath) throws IOException {
        String digest = DIGEST_MAP.get(absolutePath);
        InputStream is = new FileInputStream(absolutePath);
        String newDigest = DigestUtils.md5Hex(is);
        if (digest != null && digest.length() > 0) {
            if (digest.equals(newDigest)) {
                return false;
            }
        }
        DIGEST_MAP.put(absolutePath, newDigest);
        return true;
    }


    public static void serialize() throws IOException {
        List<String> lines = new ArrayList<>();
        for (Map.Entry<String, String> entry : DIGEST_MAP.entrySet()) {
            String line = entry.getKey() + SPLIT_CHAR + entry.getValue();
            lines.add(line);
        }
        IOUtils.writeLines(lines, "\r\n", new FileOutputStream(DIGEST_FILE), "UTF-8");
    }


    private static final String DIGEST_FILE = "C:\\Users\\Pengpeng\\.filecache";

    private static final Map<String, String> DIGEST_MAP = new HashMap();

    private static final String SPLIT_CHAR = " -> ";

    static {
        try {
            File file = new File(DIGEST_FILE);
            if (file.exists()) {
                List<String> lines = IOUtils.readLines(new FileInputStream(DIGEST_FILE), "UTF-8");
                if (lines != null) {
                    for (String line : lines) {
                        String[] str = line.split(SPLIT_CHAR);
                        DIGEST_MAP.put(str[0], str[1]);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
